<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
        添加分类
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit="false"
      highlight-current-row
      style="width: 100%"
      :row-key="row => row.id"
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <div style="padding: 10px 30px;">
            <div v-if="!props.row.products">暂无商品</div>
            <div v-else>
              <div v-for="(product, idx) in props.row.products" :key="product.id" style="margin-bottom: 6px;">
                <el-tag>{{ product.name }}</el-tag>
                <el-button type="text" size="mini" @click="removeProduct(props.row, idx)">删除</el-button>
              </div>
            </div>
            <el-input v-model="props.row.newProductName" size="small" placeholder="输入商品名称" style="width: 200px; margin-right: 8px;" />
            <el-button type="primary" size="small" @click="addProduct(props.row)">添加商品</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="ID" width="80" :resizable="false">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="分类名称" width="120" :resizable="false">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="商品数量" width="160" align="center" :resizable="false">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.productCount" :min="0" @change="onProductCountChange(scope.row)" size="small" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180" align="center" :resizable="false">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width" :resizable="false">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top: 20px;">
      <el-input v-model="newCategoryName" placeholder="新分类名称" style="width: 200px; margin-right: 8px;" />
      <el-input-number v-model="newCategoryCount" :min="0" placeholder="商品数量" style="width: 120px; margin-right: 8px;" />
      <el-date-picker v-model="newCategoryCreateTime" type="datetime" placeholder="创建时间" style="width: 200px; margin-right: 8px;" />
      <el-button type="primary" @click="quickAddCategory">快速添加分类</el-button>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker v-model="temp.createTime" type="datetime" placeholder="选择创建时间" style="width: 100%;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCategories, addCategory, updateCategory, deleteCategory } from '@/api/products/category'

export default {
  name: 'ProductCategory',
  data() {
    return {
      list: [],
      listLoading: false,
      temp: {
        id: undefined,
        name: '',
        productCount: 0,
        createTime: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑分类',
        create: '添加分类'
      },
      rules: {
        name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      },
      newCategoryName: '',
      newCategoryCount: 0,
      newCategoryCreateTime: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      this.listLoading = true
      try {
        const { data } = await getCategories()
        this.list = data.map(item => ({
          ...item,
          products: item.products || [],
          newProductName: ''
        }))
      } finally {
        this.listLoading = false
      }
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        productCount: 0,
        createTime: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(async (valid) => {
        if (valid) {
          try {
            await addCategory(this.temp)
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          } catch (error) {
            console.error('创建失败:', error)
          }
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(async (valid) => {
        if (valid) {
          try {
            await updateCategory(this.temp.id, this.temp)
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          } catch (error) {
            console.error('更新失败:', error)
          }
        }
      })
    },
    async handleDelete(row) {
      try {
        await deleteCategory(row.id)
        this.getList()
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      } catch (error) {
        console.error('删除失败:', error)
      }
    },
    onProductCountChange(row) {
      updateCategory(row.id, row)
    },
    async quickAddCategory() {
      if (!this.newCategoryName) {
        this.$message.warning('请输入新分类名称')
        return
      }
      await addCategory({ name: this.newCategoryName, productCount: this.newCategoryCount || 0, createTime: this.newCategoryCreateTime || '', products: [] })
      this.newCategoryName = ''
      this.newCategoryCount = 0
      this.newCategoryCreateTime = ''
      this.getList()
    },
    async addProduct(row) {
      if (!row.newProductName) {
        this.$message.warning('请输入商品名称')
        return
      }
      row.products = row.products || []
      const newName = row.newProductName.trim()
      if (!newName) {
        this.$message.warning('商品名称不能为空')
        return
      }
      if (row.products.some(p => p.name === newName)) {
        this.$message.warning('该商品已存在，请勿重复添加')
        row.newProductName = ''
        return
      }
      row.products.push({ id: Date.now(), name: newName })
      row.productCount = row.products.length
      row.newProductName = ''
      await updateCategory(row.id, row)
    },
    async removeProduct(row, idx) {
      row.products.splice(idx, 1)
      row.productCount = row.products.length
      await updateCategory(row.id, row)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .filter-container {
    padding-bottom: 10px;
    .filter-item {
      display: inline-block;
      vertical-align: middle;
      margin-bottom: 10px;
      margin-right: 10px;
    }
  }
}
</style> 